//
//  PaymentViewController.m
//  Article
//
//  Created by LONG on 16/5/9.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "PaymentViewController.h"
#import "LoadingView.h"

@interface PaymentViewController ()<LoadingViewDelegate>
@end

@implementation PaymentViewController{
    NSString *product;
    
    NSString *_vipID;
    NSString *_vipCost;
    NSThread *_ticketsThread;


}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.title = @"购买会员";
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"arrow"] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    [self.navigationItem.leftBarButtonItem setTintColor:UIColorFromRGB(0xffffff)];
    self.view.backgroundColor = UIColorFromRGB(0xffffff);
    [self withUIview];
    
    [self requestVipInfo];

}
- (void)withUIview{
    UIImageView *view = [[UIImageView alloc]initWithFrame:CGRectMake(WIDTH/2-100*MYWIDTH/2, 100*MYHEIGHT, 120*MYWIDTH, 120*MYWIDTH)];
    view.image = [UIImage imageNamed:@"VIP"];
    [self.view addSubview:view];
    
    self.vipCostLab = [[UILabel alloc]initWithFrame:CGRectMake(0, 250*MYHEIGHT , WIDTH, 45*MYWIDTH)];
    _vipCostLab.text = @"永久会员";
    _vipCostLab.textAlignment = NSTextAlignmentCenter;
    _vipCostLab.font = [UIFont systemFontOfSize:17];
    [self.view addSubview:_vipCostLab];
    
    self.purchase = [[UIButton alloc]initWithFrame:CGRectMake(WIDTH/2-100, 350*MYHEIGHT, 200, 30)];
    self.purchase.backgroundColor = UIColorFromRGB(MYColor);
    [self.purchase addTarget:self action:@selector(purchaseFunc) forControlEvents:UIControlEventTouchUpInside];
    [self.purchase setTitle:@"购买会员" forState:UIControlStateNormal];
    [self.purchase setTintColor:UIColorFromRGB(0xffffff)];
    [self.view addSubview:self.purchase];
    
    UILabel *xianlab = [[UILabel alloc]initWithFrame:CGRectMake(0, 410*MYHEIGHT , WIDTH, 20)];
    xianlab.text = @"----------会员专属特权----------";
    xianlab.font = [UIFont systemFontOfSize:13];
    xianlab.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:xianlab];
    
    
    UILabel *otherLab = [[UILabel alloc]initWithFrame:CGRectMake(0, HEIGHT-180, WIDTH, 120)];
    otherLab.text = @"   1、拇指营销，朋友圈免费打广告的营销利器，商家的福音！\r\r2、现有福利大放送！开通拇指营销终身会员只需298元。\r\r    3、推荐好友注册成功开通会员，即可得到高额的推荐佣金。";
    otherLab.font = [UIFont fontWithName:@"Heiti SC" size:11 * MYWIDTH];
    otherLab.numberOfLines = 0;
    otherLab.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:otherLab];
    
}
- (void)requestVipInfo{
    
    AFHTTPRequestOperationManager *manager = [MyTools initAFHttpManager];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [manager POST:@"http://wz.ijiaque.com/app/toup/vip_info.html" parameters:nil success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        if ([[responseObject objectForKey:@"status"] intValue] == 1) {

            _vipID = [NSString stringWithFormat:@"%@",[[responseObject objectForKey:@"data"][0] objectForKey:@"id"]];
            _vipCost = [NSString stringWithFormat:@"%@",[[responseObject objectForKey:@"data"][0] objectForKey:@"cost"]];
            _vipCostLab.text = [NSString stringWithFormat:@"永久会员 (%@元)",_vipCost];
        }else{
            [self.view makeToast:[responseObject objectForKey:@"info"] duration:1.0 position:CSToastPositionCenter];
        }
        
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        
        if ([MyTools connectedToNetwork] == 0) {
            [self.view makeToast:@"请检查是否联网" duration:1.0 position:CSToastPositionCenter];
        }else{
            [self.view makeToast:@"服务器错误，再试一次" duration:1.0 position:CSToastPositionCenter];
        }
    }];
}
-(void)back{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)loadImage{
    
    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
    product = @"com.thumb12341";
    if([SKPaymentQueue canMakePayments]){
        [self requestProductData:product];
    }else{
        NSLog(@"不允许程序内付费");
    }
    NSLog(@"LLLLLLLLLLLLLLLLL");
}
- (void)purchaseFunc{

    
    UIAlertController *ac = [UIAlertController alertControllerWithTitle:@"提示" message:@"你确定要去付款" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction * aa = [UIAlertAction actionWithTitle:@"前往" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [ac dismissViewControllerAnimated:YES completion:nil];
        
        [NSThread detachNewThreadSelector:@selector(loadImage) toTarget:self withObject:nil];
        
    }];
    UIAlertAction *other = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        
    }];
    [ac addAction:other];
    [ac addAction:aa];
    [self presentViewController:ac animated:YES completion:nil];
    
//    switch (1) {
//        case 1:{
//            
//
//            
//
//            break;
//        }
//            
//        default:{
//            
//            //Ping++支付
//            UIAlertController *alertSheet = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
//            //添加Button
//            [alertSheet addAction: [UIAlertAction actionWithTitle:@"支付宝支付" style: UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
//                //支付宝
//                [self pingWithVipInfo:@"alipay"];
//            }]];
//            [alertSheet addAction: [UIAlertAction actionWithTitle: @"微信支付" style: UIAlertActionStyleDefault handler:^(UIAlertAction *action){
//                //微信支付
//                [self pingWithVipInfo:@"wx"];
//            }]];
//            [alertSheet addAction: [UIAlertAction actionWithTitle: @"取消" style: UIAlertActionStyleCancel handler:nil]];
//            
//            [self presentViewController: alertSheet animated: YES completion: nil];
// 
//            
//            break;
//        }
//    }
    
    
    

}

- (void)pingWithVipInfo:(NSString *)str{
    UIAlertController *ac = [UIAlertController alertControllerWithTitle:@"提示" message:@"你确定要去付款" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction * aa = [UIAlertAction actionWithTitle:@"前往" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [ac dismissViewControllerAnimated:YES completion:nil];
        
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        NSString *urlstr = VIP_TOUP_URL;
        NSDictionary *dic = @{@"user_token":[user objectForKey:@"token"],
                              @"channel":str,//支付类型
                              @"rank_id":_vipID};
        
        AFHTTPRequestOperationManager *manager=[AFHTTPRequestOperationManager manager];
        manager.responseSerializer=[AFHTTPResponseSerializer serializer];
        
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        
        
        [manager POST:urlstr parameters:dic success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            NSDictionary *dic1 = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
            //NSLog(@"///%@",dic1);
            
            if ([[dic1 objectForKey:@"status"] intValue] == 0) {
                [self.view makeToast:[dic1 objectForKey:@"info"] duration:1.0 position:CSToastPositionCenter];
                
            }else{
                
                if ([str isEqualToString:@"alipay"]) {
                    
                    [self alipayShop:dic1];
                    
                }else{
                    [self wxShop:dic1];
                }
            }
        } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {

            [MBProgressHUD hideHUDForView:self.view animated:YES];
            
            if ([MyTools connectedToNetwork] == 0) {
                [self.view makeToast:@"请检查是否联网" duration:1.0 position:CSToastPositionCenter];
            }else{
                [self.view makeToast:@"服务器错误，再试一次" duration:1.0 position:CSToastPositionCenter];
            }
            
        }];
        
    }];
    UIAlertAction *other = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        
    }];
    [ac addAction:other];
    [ac addAction:aa];
    [self presentViewController:ac animated:YES completion:nil];
}

#pragma mark 支付宝
- (void)alipayShop:(NSDictionary *)dic{
    NSString *alipaystrUrl = @"appyrgiug56hy53g2h64t6";
    
    //NSLog(@"---%@",dic);
    //支付宝显示网页版
    self.views = [[UIApplication sharedApplication] windows];
    UIWindow* windowtemp = _views[0];
    
    if (windowtemp.hidden) {
        windowtemp.hidden = NO;
    }
    else
    {
        NSLog(@"no hidden");
    }
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"alipay://"]]) {
        
        windowtemp.hidden = YES;
    }
    //跳转支付宝
    
    [Pingpp createPayment:[dic objectForKey:@"data"]
           viewController:self
             appURLScheme: alipaystrUrl
           withCompletion:^(NSString *result, PingppError *error) {
               windowtemp.hidden = YES;
               
               if ([result isEqualToString:@"success"]) {
                   // 支付成功
                   NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
                   [user setObject:@"1" forKey:@"agents_level"];
                   [user synchronize];
                   
                   UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"恭喜您成为我们的会员" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
                   [alert show];
                   
                  
               } else {
                   // 支付失败或取消
                NSLog(@"Error: code=%lu msg=%@", (unsigned long)error.code, [error getMsg]);
               }
           }
     ];
    
}

#pragma mark 微信支付

- (void)wxShop:(NSDictionary *)dic{
    
    if ([WXApi isWXAppInstalled]) {
        NSString *wxstrUrl = @"wx24f1f8198ba7b121";
        
        //跳转微信
        //Pingpp *p = [[Pingpp alloc]init];
        [Pingpp createPayment:[dic objectForKey:@"data"]
               viewController:self
                 appURLScheme: wxstrUrl
               withCompletion:^(NSString *result, PingppError *error) {
                   
                   if ([result isEqualToString:@"success"]) {
                       // 支付成功
                       NSLog(@"成功");
                       NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
                       [user setObject:@"1" forKey:@"agents_level"];
                       [user synchronize];

                       UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"恭喜您成为我们的会员" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
                       [alert show];

                    
                   } else {
                       // 支付失败或取消
                       NSLog(@"Error: code=%lu msg=%@", (unsigned long)error.code, [error getMsg]);
                   }
               }
         ];
    }else{
        [self.view makeToast:@"支付失败" duration:1.0 position:CSToastPositionCenter];
    }
    
}

//请求商品
- (void)requestProductData:(NSString *)type{
    
    [[LoadingView shareLoadingView] show];
    [LoadingView shareLoadingView].delegate = self;

    NSLog(@"-------------请求对应的产品信息----------------");
    NSArray *product = [[NSArray alloc] initWithObjects:type, nil ];
    
    NSSet *nsset = [NSSet setWithArray:product];
    SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:nsset];
    request.delegate = self;
    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
    [request start];
    
}
- (void)closeLoadingView{
    NSLog(@"11111111");
    [NSThread exit];
}
//收到产品返回信息
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response{
    
   [[LoadingView shareLoadingView] close];


    NSLog(@"--------------收到产品反馈消息---------------------");
    NSArray *product = response.products;
    if([product count] == 0){
        NSLog(@"--------------没有商品------------------");
        return;
    }
    
    NSLog(@"productID:%@", response.invalidProductIdentifiers);
    NSLog(@"产品付费数量:%zd",[product count]);
    
    SKProduct *p = nil;
    for (SKProduct *pro in product) {
        NSLog(@"%@", [pro description]);
        NSLog(@"%@", [pro localizedTitle]);
        NSLog(@"%@", [pro localizedDescription]);
        NSLog(@"%@", [pro price]);
        NSLog(@"%@", [pro productIdentifier]);
        
        if([pro.productIdentifier isEqualToString:@"com.thumb12341"]){
            p = pro;
        }

    }
    
    SKPayment *payment = [SKPayment paymentWithProduct:p];
    
    NSLog(@"发送购买请求");
    [[SKPaymentQueue defaultQueue] addPayment:payment];
}
//请求失败
- (void)request:(SKRequest *)request didFailWithError:(NSError *)error{
    NSLog(@"------------------错误-----------------:%@", error);
}

- (void)requestDidFinish:(SKRequest *)request{
    NSLog(@"------------反馈信息结束-----------------");
}


//监听购买结果
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transaction{
    for(SKPaymentTransaction *tran in transaction){
        
        switch (tran.transactionState) {
            case SKPaymentTransactionStatePurchased:{
                NSLog(@"交易完成");
                [self completeTransaction:tran];
                
                
                NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
                [user setObject:@"1" forKey:@"agents_level"];
                [user synchronize];
                
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"恭喜您成为我们的会员" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
                [alert show];
                
                NSLog(@"成功");
                [self back];
                break;

            }
            case SKPaymentTransactionStatePurchasing:
                NSLog(@"商品添加进列表");
                
                break;
            case SKPaymentTransactionStateRestored:
                NSLog(@"已经购买过商品");
                
                break;
            case SKPaymentTransactionStateFailed:
                NSLog(@"交易失败");
                
                break;
            default:
                break;
        }
    }
}

//交易结束
- (void)completeTransaction:(SKPaymentTransaction *)transaction{
    NSLog(@"交易结束");
    NSString * productIdentifier = transaction.payment.productIdentifier;
    NSLog(@"::::%@",productIdentifier);
    if ([productIdentifier length] > 0) {
        // 向自己的服务器验证购买凭证
    }
    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
}
- (void)failedTransaction:(SKPaymentTransaction *)transaction {
    if(transaction.error.code != SKErrorPaymentCancelled) {
        NSLog(@"购买失败");
    } else {
        NSLog(@"用户取消交易");
    }
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    
    if ([[user objectForKey:@"agents_level"] intValue] > 0) {
        [_purchase setTitle:@"会员无需再次购买" forState:UIControlStateNormal];
        _purchase.backgroundColor = UIColorFromRGB(0x666666);
        _purchase.userInteractionEnabled = NO;
    }
    
    self.tabBarController.tabBar.hidden = YES;
    self.tabBarController.tabBar.translucent = YES;
    
}
@end
